package vip.xiaonuo.biz.modular.iot.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.modular.iot.result.VideoEventStreamVO;
import vip.xiaonuo.biz.modular.iot.result.VideoInfoVO;
import vip.xiaonuo.biz.modular.iot.result.VideoLiveStreamVO;
import vip.xiaonuo.biz.modular.iot.service.VideoService;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.util.SignTool;
import vip.xiaonuo.dev.api.DevConfigApi;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class VideoServiceImpl implements VideoService {
    @Resource
    private DevConfigApi devConfigApi;

    public List<VideoInfoVO> queryCameraList(String deviceCode) {
        String iotUrl = devConfigApi.getValueByKey("IOT_URL");
        if (ObjectUtil.isEmpty(iotUrl)) throw new CommonException("IOT_URL未正确配置");
        String iotToken = devConfigApi.getValueByKey("IOT_TOKEN");
        if (ObjectUtil.isEmpty(iotToken)) throw new CommonException("IOT_TOKEN未正确配置");

        List<VideoInfoVO> resultList = new ArrayList<>();
        String param = String.format("equipmentCode=%s", deviceCode);
        String sign = SignTool.signMd5Hex(param, iotToken);
        final String url = String.format("%s/api/videos/getVideoCode?%s&sign=%s", iotUrl, param, sign);
        try {
            String respStr = HttpUtil.get(url);
            log.info("respStr={}", respStr);
            JSONObject jsonObject = JSONObject.parseObject(respStr);
            Assert.isTrue(jsonObject.getBooleanValue("success"), jsonObject.getString("msg"));
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                VideoInfoVO vo = new VideoInfoVO();
                vo.setVideoCode(item.getString("vidoeCode"));
                vo.setVideoName(item.getString("videoName"));
                resultList.add(vo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(String.format("调用视频接口异常，设备接口提示：%s", e.getMessage()));
        }
        return resultList;
    }

    @Override
    public VideoLiveStreamVO queryLiveStreamUrl(String deviceCode, String videoCode) {
        String iotUrl = devConfigApi.getValueByKey("IOT_URL");
        if (ObjectUtil.isEmpty(iotUrl)) throw new CommonException("IOT_URL未正确配置");
        String iotToken = devConfigApi.getValueByKey("IOT_TOKEN");
        if (ObjectUtil.isEmpty(iotToken)) throw new CommonException("IOT_TOKEN未正确配置");

        String param = String.format("equipmentCode=%s&videoCode=%s&videoStream=%s", deviceCode, videoCode, "02");
        String sign = SignTool.signMd5Hex(param, iotToken);
        final String url = String.format("%s/api/videos/getRealplay?%s&sign=%s", iotUrl, param, sign);
        log.info("url={}", url);
        String respStr = HttpUtil.get(url);
        log.info("respStr={}", respStr);
        JSONObject jsonObject = JSONObject.parseObject(respStr);
        Assert.isTrue(jsonObject.getBooleanValue("success"), "获取视频播放地址失败");
        JSONObject data = jsonObject.getJSONObject("data");
        VideoLiveStreamVO vo = new VideoLiveStreamVO();
        vo.setVideoCode(data.getString("videoCode"));
        vo.setVideoUrl(String.format("%s%s", iotUrl, data.getString("realplayPath")));
        return vo;
    }

    @Override
    public VideoEventStreamVO queryEventStreamUrl(String eventId) {
        String iotUrl = devConfigApi.getValueByKey("IOT_URL");
        if (ObjectUtil.isEmpty(iotUrl)) throw new CommonException("IOT_URL未正确配置");
        String iotToken = devConfigApi.getValueByKey("IOT_TOKEN");
        if (ObjectUtil.isEmpty(iotToken)) throw new CommonException("IOT_TOKEN未正确配置");

        String param = String.format("sensoreventid=%s", eventId);
        String sign = SignTool.signMd5Hex(param, iotToken);
        final String url = String.format("%s/api/videos/h5videosAndSensor?%s&sign=%s", iotUrl, param, sign);
        log.info("url={}", url);
        String respStr = HttpUtil.get(url);
        log.info("respStr={}", respStr);
        JSONObject jsonObject = JSONObject.parseObject(respStr);
        Assert.isTrue(jsonObject.getBooleanValue("success"), String.format("获取事件播放地址失败,%s", jsonObject.getString("msg")));
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray videos = data.getJSONArray("videos");

        List<VideoEventStreamVO.Video> videoList = new ArrayList<>();
        for (int i = 0; i < videos.size(); i++) {
            JSONObject item = videos.getJSONObject(i);
            VideoEventStreamVO.Video video = new VideoEventStreamVO.Video();
            video.setVideoCode(item.getString("videoCode"));
            video.setVideoName(item.getString("videoName"));
            String videoUrl = item.getString("videoPath");
            Assert.isTrue(StringUtils.isNotEmpty(videoUrl) && !videoUrl.endsWith("null"), "视频流未缓存完毕，请稍后点击重试");
            video.setVideoUrl(String.format("%s%s", iotUrl, videoUrl));
            videoList.add(video);
        }
        List<VideoEventStreamVO.Event> eventList = new ArrayList<>();
        JSONObject eventData = data.getJSONObject("sensorLogmap");
        eventData.forEach((key, value) -> {
            JSONArray jsonArray = (JSONArray) value;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                VideoEventStreamVO.Event event = new VideoEventStreamVO.Event();
                event.setTime(item.getDate("happenAt"));
                event.setTitle(item.getString("title"));
                event.setValue(item.getString("valueText"));
                eventList.add(event);
            }
        });
        VideoEventStreamVO vo = new VideoEventStreamVO();
        vo.setEventList(eventList);
        vo.setVideoList(videoList);
        return vo;
    }
}
